package com.example.msg;

import android.util.Log;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.UUID;

/****
 * http请求工具类
 */
public class Client {

    public static final String TAG = "P2P:";
    public static Boolean isRun=false;
    public static void start(){
        isRun=true;
        new Thread(){
            @Override
            public void run() {
                process();
            }
        }.start();
    }
    public static void stop(){
        isRun=false;
    }
    private static void process(){

        try {
            int appPort=5858;
            int buffSize=1024*4;
            String appIp="47.101.52.109";
            Log.i(TAG, "连接服务器: "+appIp+" , "+appPort);
            byte[]buff=new byte[buffSize];
            DatagramSocket dSocket=new DatagramSocket();
            DatagramPacket pkg=new DatagramPacket(buff,buffSize);

            InetAddress address=InetAddress.getByName(appIp);
            String text="client:zhang";
            byte[] data=text.getBytes();
            DatagramPacket sendPkg=new DatagramPacket(data, data.length, address, appPort);
            dSocket.send(sendPkg);
            Log.i(TAG, "客户端发送完毕等待回包:::::::");
            dSocket.receive(pkg);
            String str=new String(pkg.getData(),0,pkg.getLength());
            Log.i(TAG, str);
            //开始给服务器发送数据
            String[]param=str.split(",");
            String ip=param[0];
            int port=Integer.parseInt(param[1]);
            while(isRun) {
                String uuid=UUID.randomUUID().toString();
                String dt="msg:\t"+uuid;
                sendDate(dSocket, ip, port, dt);
                //Thread.sleep(2000);
                Log.i(TAG, "服务器IP信息:"+str);
                Log.i(TAG, "发送数据:"+dt+"\r\n\r\n");
                Thread.sleep(200);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private static void sendDate(DatagramSocket socket,String ip,int port,String data) {
        try {
            InetAddress address=InetAddress.getByName(ip);
            DatagramPacket pkgSend=new DatagramPacket(data.getBytes(),data.getBytes().length,address,port);
            socket.send(pkgSend);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}
